package peer.model.transfer.runnable;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

import peer.model.transfer.TransfersManager;


public class UploadInstance implements Runnable {

	private Socket sckClient;
	private Scanner inStr;
	private boolean finished;
	private String ipHost;
	private Integer port;

	public UploadInstance(Socket sck){
		this.sckClient=sck;
		this.ipHost=this.sckClient.getInetAddress().getHostAddress();
		this.port=this.sckClient.getLocalPort();
		try {
			this.inStr=new Scanner(this.sckClient.getInputStream());
			System.out.println("[PEER/UPLOAD] Connected to: " + this.ipHost + ":" + this.port);
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}
	}

	public void finish(){
		this.finished=true;
	}

	public boolean isFinished(){
		return this.finished;
	}

	@Override
	public void run() {
		System.out.println("[PEER/UPLOAD] " + Thread.currentThread() + " started.");
		try{
			if(inStr.hasNextLine()){
				//check response type, filename, size, block
				TransfersManager.startUpload(this.sckClient, inStr.nextLine());
			}
		}finally{
			try {
				this.sckClient.close();
				System.out.println("[PEER/UPLOAD] Disconnected from: " + this.ipHost + ":" + this.port);
				System.out.println("[PEER/UPLOAD] " + Thread.currentThread() + " ended.");
			} catch (IOException e) {
				e.printStackTrace(System.err);
			}
		}
	}
}
